//
//  HDApplyIndemnityThreeVC.swift
//  HuaDaoPeifu
//
//  Created by 刘杰 on 2018/7/24.
//  Copyright © 2018年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD

class HDApplyIndemnityThreeVC: UITableViewController {
    
    var caseModel : HDCaseModel?
    var recognizee : HDRecognizeeModel?
    var policyno : String?
    var info_id : String?
    
    fileprivate var header : HDApplyIndemnityThreeVCHeaderView?
    fileprivate var cells = [HDApplyIndemnityArchivesCell]()
    fileprivate var identityCell : HDApplyIndemnityArchivesCell?
    fileprivate let orangeColor = UIColor.init(red: 253.0/255.0, green: 152.0/255.0, blue: 39.0/255.0, alpha: 1)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupTableView()
        setupArchiveCells()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        identityCell?.refreshPhotoView()
    }
    
    /// 根据数据，创建cell
    func setupArchiveCells() {
        
        guard let caseModel = caseModel,
        let datatype = caseModel.datatype,
        let bdatatype = caseModel.bdatatype_list else {
            return
        }
        
        let types = datatype.split(separator: ",")
        let necessary = bdatatype.split(separator: ",")
        
        for i in 0..<types.count {
            let type = types[i]
            let nib = UINib(nibName: "HDApplyIndemnityArchivesCell", bundle: nil)
            let cell = nib.instantiate(withOwner: nil, options: nil).last as! HDApplyIndemnityArchivesCell
            
            cell.isNecessary = necessary.contains(type)
            cell.key = type.description
            if let datatypeimg = caseModel.datatypeimg,
            let datatypeimgs = datatypeimg[type.description] ?? "" {
                let urls = datatypeimgs.split(separator: ",")
                cell.model.demoUrls = urls
                
                var urlStrings = [String]()
                //模型数据数组
                for url in urls {
                    urlStrings.append(kBaseApiv2URL+"/picc"+url.description)
                    
                }
                
                cell.showDemoImages = {[unowned self]
                    (cell) in
                    let vc = JZAlbumViewController()
                    vc.imgArr = urlStrings as [Any]
                    self.navigationController?.present(vc, animated: true, completion: nil)
                }
            }
            
            cell.photoViewChangeHeightBlock = {[unowned self](cell) in
                // 这里必须全表格reload，不能单纯reload某一行，否则会出现单元格错乱的问题
                self.tableView.reloadData()
            }
            
            if type.description == "identity" {
                // 请求身份证图片
                loadImageData(cell)
                identityCell = cell
                continue
            }
            cells.append(cell)
        }
        
        if let identifierCell = identityCell{
            cells.append(identifierCell)
        }
        tableView.reloadData()
        
    }
    
    func setupFooterView() {
        let footer = UIView.init(frame: CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: 70))
        footer.backgroundColor = UIColor.clear
        
        tableView.tableFooterView = footer
        
        // 上一步
        let back = UIButton(type: UIButtonType.custom)
        back.addTarget(self, action: #selector(HDApplyIndemnityThreeVC.back), for: UIControlEvents.touchUpInside)
        back.setTitle("上一步", for: UIControlState.normal)
        back.setTitleColor(orangeColor, for: UIControlState.normal)
        back.layer.borderColor = orangeColor.cgColor
        back.layer.borderWidth = 1
        back.layer.masksToBounds = true
        back.layer.cornerRadius = 4
        footer.addSubview(back)
        
        back.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.height.equalTo(40)
            make.right.equalTo(footer.snp.centerX).offset(-5)
            make.centerY.equalToSuperview()
        }
        // 确认提交
        let confirm = UIButton(type: UIButtonType.custom)
        confirm.addTarget(self, action: #selector(HDApplyIndemnityThreeVC.confirm), for: UIControlEvents.touchUpInside)
        confirm.setTitle("确认提交", for: UIControlState.normal)
        confirm.setTitleColor(UIColor.white, for: UIControlState.normal)
        confirm.backgroundColor = orangeColor
        confirm.layer.masksToBounds = true
        confirm.layer.cornerRadius = 4
        footer.addSubview(confirm)
        
        confirm.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-10)
            make.height.equalTo(40)
            make.left.equalTo(footer.snp.centerX).offset(5)
            make.centerY.equalToSuperview()
        }
    }
    
    func back() {
        navigationController?.popViewController(animated: true)
    }
    
    func confirm() {
        
        for cell in cells {
            if cell.isNecessary! && cell.model.allPhotos.count <= 0 {
                HDIdentityTipsView.initHDIdentityTipsView(showMessage: "请上传 \(cell.title!) 附件")
                return
            }
        }
        
        
        let group = DispatchGroup.init()
        let queue = DispatchQueue.init(label: "upload")
        SVProgressHUD.showDisableLoading("正在提交数据...")
        
        var photosCount = 0
        for cell in cells {
            photosCount += cell.model.allPhotos.count
        }
        
        var index = 1
        for cell in cells {
            for photo in cell.model.allPhotos {
                
                if let imageData = UIImageJPEGRepresentation(photo, 1.0) {
                    let base64String = "data:image/jpeg;base64," + imageData.base64EncodedString()// "data:image/jpeg;base64,"+imageData.base64EncodedString()
                    
                    // FIXME: -这里暂时停止开发了
                    group.enter()
                    HDApiManagerHandler.uploadCaseImage(base64String, String(photosCount), cell.key!, String(index), (caseModel?.case_id)!, policyno!) { (result) in
                        group.leave()
                        guard let result = result else{
                            print("上传失败")
                            return
                        }
                        if result.status == .Success {
                            print("成功上传一张")
                        }else {
                            print("一张图片上传失败")
                        }
                    }
                    index = index + 1
                }
            }
        }
        
        
        group.notify(queue: queue) {[unowned self] in
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now(), execute: {[unowned self] in
                SVProgressHUD.dismiss()
                
                let str1 = NSAttributedString(string: "此次理赔案件的ID号为：", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 18)])
                let id = NSAttributedString(string: "\(String(describing: self.caseModel == nil ? "" : self.caseModel!.case_id)) \n\n", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 15),NSForegroundColorAttributeName:UIColor.orange])
                
                let tip1 = NSAttributedString(string: "您的理赔申请已经提交成功，工作人员会在3-5个工作日进行审核！\n\n", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 15),NSForegroundColorAttributeName:UIColor.lightGray])
                let tip2  = NSAttributedString(string: "处理进度请到“档案追踪”中查看", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 15),NSForegroundColorAttributeName:UIColor.lightGray])
                
                let strM = NSMutableAttributedString(attributedString: str1)
                strM.append(id)
                strM.append(tip1)
                strM.append(tip2)
                HDIdentityTipsView.showSuccessTip(showMessage: strM, {
                    self.navigationController?.popToRootViewController(animated: true)
                })
            })
        }
    }
    
    func setupTableView() {
        
        let nib = UINib(nibName: "HDApplyIndemnityThreeVCHeaderView", bundle: nil)
        
        let headerContentView = nib.instantiate(withOwner: nil, options: nil).last as? HDApplyIndemnityThreeVCHeaderView
        headerContentView?.showDetail = {[unowned self] in
            if let case_id = self.caseModel?.case_id,
                let info_id = self.info_id
                {
                
                let nib = UINib(nibName: "HDPreviewViewController", bundle: nil)
                let vc = nib.instantiate(withOwner: nil, options: nil).last as! HDPreviewViewController
                vc.case_id = case_id
                vc.info_id = info_id
                self.navigationController?.pushViewController(vc, animated: true)
            }
            
        }
        
        let header = UIView.init(frame: CGRect(x: 0, y: 0, width: AppConstant.screenWidth, height: (headerContentView?.frame.height)!))
        
        tableView.tableHeaderView = header
        header.addSubview(headerContentView!)
        self.header = headerContentView
        self.header?.nameLB.text = recognizee?.partone?.name
        headerContentView?.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
        })
        
        setupFooterView()
        
        // tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        tableView.dataSource = self
        
        tableView.rowHeight = 175
        tableView.sectionHeaderHeight = 10
        tableView.sectionFooterHeight = 1
    }
    
    func loadImageData(_ cell:HDApplyIndemnityArchivesCell) {
        if let subStrings = recognizee?.partone?.images.split(separator: ","),
            let urls = cropImageUrls(subStrings) {
            cell.manager?.addNetworkingImage(toAlbum: urls, selected: true)
            cell.manager?.configuration.photoMaxNum = 2
        }
        // FIXME: - 这里照片获取路径应该是请求接口，之后需要修改
//        HDApiManagerHandler.requestPartthreeIdPic(info_id!, (caseModel?.case_id)!) { (images) in
//            print(images)
//        }
        
    }
    
    /// 裁切图片地址
    func cropImageUrls(_ relativeUrls:[String.SubSequence]?) -> [String]? {
        guard let relativeUrls = relativeUrls else {
            return nil
        }
        var urls = [String]()
        for url in relativeUrls {
            
            if url.first == "."{
                if url.startIndex != Substring.Index.init(encodedOffset: 0){
                    continue
                }
                urls.append(kBaseApiv2URL + "/picc" + url.substring(from: url.index(url.startIndex, offsetBy: 2)))
            }else {
                urls.append(kBaseApiv2URL + url)
            }
        }
        return urls
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return cells.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = cells[indexPath.section]
        return cell
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cell = cells[indexPath.section]
        let height = cell.model.photoViewHeight
        return height
    }
}
